﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Application.UserApp;
using JFnetcore.Models;
using Microsoft.AspNetCore.Http;
using Utility;
using Domain.Entities;
using Application.RoleMenuApp;
using Microsoft.AspNetCore.Http.Features;
using Application.LogApp;
using static Utility.EnumUtil;

namespace JFnetcore.Controllers
{
    public class LoginController : Controller
    {
        private IUserAppService _userAppService;
        private IRoleMenuAppService _rolemenuAppService;
        private ILogAppService _logAppService;
        public LoginController(IUserAppService userAppService, IRoleMenuAppService rolemenuAppService, ILogAppService logAppService)
        {
            _userAppService = userAppService;
            _rolemenuAppService = rolemenuAppService;
            _logAppService = logAppService;
        }

        /// <summary>
        /// 打开登录首页视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(string id)
        {
            if (id == "out")
                HttpContext.Session.Remove("CurrentUser");
            return View();
        }

        /// <summary>
        /// 表单提交，登陆接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                //检查用户信息
                var user = _userAppService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    if (user.Disable == 1)
                    {
                        List<RoleMenu> list = _rolemenuAppService.GetAll(user.Role_id.ToString());
                        SessionModel smodel = new SessionModel();
                        smodel.IP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                        smodel.User = user;
                        smodel.RolemenuList = list;
                        //记录Session
                        HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(smodel));

                        _logAppService.Add(DateTime.Now, smodel.IP, user.Id.ToString(), (int)OperationEnum.Login, "");

                        //跳转到系统首页
                        return RedirectToAction("Index", "Home");

                    }
                    else
                    {
                        ViewBag.ErrorInfo = "无登录权限  " + user.Disabledesc;
                        return View();
                    }
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }

        /// <summary>
        /// 游客按钮登录接口
        /// </summary>
        /// <returns></returns>
        public IActionResult YKlogin()
        {
            var user = _userAppService.CheckUser("visitor", "123123");
            List<RoleMenu> list = _rolemenuAppService.GetAll(user.Role_id.ToString());
            SessionModel smodel = new SessionModel()
            {
                IP = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                User = user,
                RolemenuList = list
            };
            //记录Session
            HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(smodel));
            _logAppService.Add(DateTime.Now, smodel.IP, user.Id.ToString(), (int)OperationEnum.Login, "游客按钮直接登录");
            //跳转到系统首页
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public IActionResult SendEmail(string loginname,string email)
        {
            if (!string.IsNullOrEmpty(loginname) && !string.IsNullOrEmpty(email))
            {
                User umodel = _userAppService.GetByLoginname(loginname);
                if (umodel != null)
                {
                    if (umodel.User_email != email)
                    {
                        return Content(ReturnJsonHelp.OutHandlerJson(false, "邮箱错误！"));
                    }
                    else
                    {
                        #region 生成密码
                        int number;
                        string strCode = string.Empty;
                        //随机数种子
                        Random random = new Random();

                        for (int i = 0; i < 6; i++) //校验码长度为4
                        {
                            //随机的整数
                            number = random.Next();

                            //字符从0-9,A-Z中随机产生,对应的ASCII码分别为
                            //48-57,65-90
                            number = number % 36;
                            if (number < 10)
                            {
                                number += 48;
                            }
                            else
                            {
                                number += 55;
                            }
                            strCode += ((char)number).ToString();
                        }
                        string newPwd = strCode;
                        #endregion
                        umodel.User_pwd = newPwd;
                        if (_userAppService.AddOrUpdate(umodel))
                        {
                            MailUtil.Send(email, "金帆系统【找回密码】", "新密码：" + newPwd);
                            return Content(ReturnJsonHelp.OutHandlerJson(true, "邮件已经发送！"));
                        }
                        else
                        {
                            return Content(ReturnJsonHelp.OutHandlerJson(false, "初始密码失败！"));
                        }
                    }
                }
                else
                {
                    return Content(ReturnJsonHelp.OutHandlerJson(false, "账号不存在！"));
                }
            }
            else
            {
                return Content(ReturnJsonHelp.OutHandlerJson(false, "账号与邮件必填！"));
            }
        }
    }
}
